import { promisifyAll } from 'miniprogram-api-promise';
const wxp = {}
// promisify all wx's api
promisifyAll(wx, wxp)
import {
  getOpenid,
  pushUserInfo
} from "./api/user"
//app.js
App({
  wxp,
  onLaunch: function () {
    this.getOpenid().then(openid => {
      this.globalData.openid = openid
    });
  },
  globalData: {
    userInfo: null,
    openid:''
  },
  // 更新个人信息
  pushUserInfo(){
    wxp.getUserInfo().then(res=>{
      pushUserInfo(this.globalData.openid,res)
    })
  },
  // 判断是否登陆
  _checkLogin() {
    var token = wxp.getStorageSync("token");
    if (token) {
      return true;
    }
    return false;
  },
  getJscode() {
    return new Promise((res) => {
      wxp.login({
        success: resp => {
          res(resp.code)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
        }
      })
    })
  },
  // 获取openid
  getOpenid() {
    return new Promise((res, rej) => {
      this.getJscode().then(code => {
        getOpenid({
          jsCode: code
        }).then(resp => {
          if (resp.code == 0) {
            wx.setStorageSync(
              'openid',
              resp.data.openid
            )
          }
          res(resp.data.openid)
        }).catch(err => {
          rej(err)
        })
      })
    })


  }
})